/*
 * @Author: chunlai
 * @Date: 2023-12-07 08:51:58
 * @LastEditTime: 2025-02-08 11:11:49
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \01.latest-short-insure\src\store\modules\risks.js
 * @Description:保费试算
 */
import { Dialog } from "vant";
import { validRules } from "@/translate/risks/rules";
import { GetToRateparams } from "@/translate/risks/rate";
import { apiGetRate } from "@/utils/functions";

const state = [];
const getters = {
  mainInsu: (state) => {
    return state.filter((todo) => todo.ismain);
  },
  subRisk: (state) => {
    return state.filter((todo) => !todo.ismain);
  },
  showedRisks: (state) => {
    return state.filter((todo) => todo.ismain || todo.checked);
  },
  allRisk: (state) => {
    return state;
  },
};
const mutations = {
  // 险种字段赋值
  SET_RISKSTATE(state, data) {
    if (data) {
      for (let i = 0; i < data.length; i++) {
        state[i] = data[i];
      }
    }
  },
  /**
   * 试算接口返回数据: 回显保费
   * @param {*} state
   * @param {*} data
   */
  SET_RISKRATE(state, data) {
    // console.log('试算:', data);
    for (let j = 0; j < data.length; j++) {
      for (let i = 0; i < state.length; i++) {
        if (state[i].varietyCode == data[j].varietyCode) {
          state[i].prem = data[j].prem || data[j].subPrem || "0";
          state[i].amnt = data[j].amnt || "";
          // 责任列表回显
          if (data[j].premDutyList && data[j].premDutyList.length > 0) {
            state[i].liabilityList.forEach((e) => {
              const fdObj2 = data[j].premDutyList.find(
                (dty) => dty.dutyCode == e.dutyCode
              );
              if (fdObj2) {
                e.prem = fdObj2.prem;
                e.amnt = fdObj2.amnt;
              }
            });
          }
        }
      }
    }
    state = state.splice(1, 0);
  },
  // 继续投保---> 数据库险种信息(translate\risks\insert.js GetRiskData预处理)
  SET_RISKS_DATA(state, data) {
    // console.log('SET_RISKS_DATA', data);
    for (let j = 0; j < data.length; j++) {
      for (let i = 0; i < state.length; i++) {
        if (state[i].varietyCode == data[j].varietyCode) {
          if (data[j].prem) {
            state[i].prem = data[j].prem;
          }
          if (data[j].amnt) {
            state[i].amnt = data[j].amnt;
          }
          if (data[j].insuYear) {
            if (state[i].insureYearList && state[i].insureYearList.length > 0) {
              state[i].insuYear = data[j].insuYear;
            }
          }
          if (data[j].payendyear) {
            state[i].payendyear = data[j].payendyear;
          }
          if (data[j].checked) {
            state[i].checked = data[j].checked;
          }
          state[i].mult = data[j].mult || "1";
          // if (data[j].renewFlag) {
          //   state[i].renewFlag = data[j].renewFlag;
          // }
          if (data[j].planCode !== void 0) {
            state[i].planCode = data[j].planCode;
            if (state[i].showLiabilities) {
              const tranObj = state[i].jibenTrans;
              let tranStr = "",
                tranArr = [];
              // 可选责任转化的
              let dutys = state[i].dutyPlanList;
              for (let key in tranObj) {
                if (tranObj[key] == data[j].planCode) {
                  tranStr = `${key}`;
                }
              }
              tranArr = tranStr.split("");
              dutys.forEach((tagDut) => {
                if (tranArr.includes(tagDut.dutyCode)) {
                  tagDut.isChecked = true;
                }
              });
              state[i].dutyPlanList = JSON.parse(JSON.stringify(dutys));
            }
          }
          // 可选责任列表
          // if (data[j].dutys && data[j].dutys.length > 0) {
          //   state[i].liabilityList.forEach((e) => {
          //     data[j].dutys.forEach((dut) => {
          //       if (dut.dutyCode == e.dutyCode) {
          //         e.prem = dut.dutyPrem;
          //         e.amnt = dut.dutyAmnt;
          //         e.isChecked = true;
          //       }
          //     });
          //   });
          // }
        }
      }
    }
    state = state.splice(1, 0);
  },
};
const actions = {
  //  险种信息校验
  setValidate({ state, rootState, commit }, payload) {
    return new Promise((reslove, reject) => {
      let flag = true;
      let content = validRules(state, payload, rootState);
      commit("SET_RISKSTATE", content);
      if (flag) {
        reslove("设置险种信息成功");
      } else {
        reject("险种校验失败");
      }
    });
  },
  // 设置险种信息
  setRisks({ dispatch, rootState, commit, state }, data) {
    return new Promise((reslove, reject) => {
      // 1.校验险种规则
      dispatch("setValidate", data)
        .then((res) => {
          // 2.保费试算
          const pageStore = rootState.page;
          // console.log(pageStore);
          // 注意: index中配置"noInsureCount"时,不需要保费试算(常为短险),有计划直接赋值保额/保费,或其他形式
          if (pageStore.noInsCount) {
            commit(
              "insert/UPDATE_PAYINFO",
              { totalPrem: state[0].prem },
              { root: true }
            );
            commit("SET_RISKRATE", state);
          } else {
            dispatch("getRateData")
              .then((res) => {
                reslove("");
              })
              .catch((err) => {
                reject("计算错误");
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    });
  },
  getRateData({ state, rootState, commit, rootGetters, dispatch }) {
    return new Promise((reslove, reject) => {
      // 共通方法获取请求参数
      let params = GetToRateparams(rootState, rootGetters);
      // console.log("getRateData---", params);
      params.workNum = rootState.workNum;
      commit("updateLoad", true, { root: true });
      apiGetRate(params)
        .then(({ data }) => {
          commit("updateLoad", false, { root: true });
          if (data.code == 1) {
            let infos = {};
            if (["ansheng"].includes(rootState.gysEngName)) {
              infos = data;
            } else {
              infos = data.dataLists[0];
            }
            // console.log(infos);
            let totalPrem = infos.prem;
            commit(
              "insert/UPDATE_PAYINFO",
              { totalPrem: totalPrem },
              { root: true }
            );
            // 安盛特殊处理
            if (["ansheng"].includes(rootState.gysEngName)) {
              infos.productList[0].varietyCode = rootState.mainRiskCode;
            }
            commit("SET_RISKRATE", infos.productList);
            reslove("费率计算完成");
          } else {
            Dialog.alert({
              title: "提示",
              message: data.msg,
            }).then(() => {
              reject("计算出现异常");
            });
          }
        })
        .catch((err) => {
          commit("updateLoad", false, {
            root: true,
          });
          console.log(err);
        });
    });
  },
};
export default {
  namespaced: true, //用于在全局引用此文里的方法时标识这一个的文件名
  state,
  getters,
  mutations,
  actions,
};
